//
//  ViewController.m
//  addChildViewController
//
//  Created by -_Kazuto on 16/11/6.
//  Copyright © 2016年 David. All rights reserved.
//

#import "SwitchingViewController.h"
#import "BlueViewController.h"
#import "YellowViewController.h"


@interface SwitchingViewController ()
@property (nonatomic,strong)BlueViewController *blueVC;
@property (nonatomic,strong)YellowViewController *yellowVC;

@end

@implementation SwitchingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.blueVC=[self.storyboard instantiateViewControllerWithIdentifier:@"blue"];
    self.yellowVC=[self.storyboard instantiateViewControllerWithIdentifier:@"yellow"];
    [self switchViewFromViewController:nil toViewController:self.blueVC];
}

-(IBAction)swichViews:(id)sender{
    if(!self.yellowVC.view.superview){
        if(!self.yellowVC.view){
            self.yellowVC=[self.storyboard instantiateViewControllerWithIdentifier:@"yellow"];
        }
    }
    else {
        if(!self.blueVC.view){
            self.blueVC=[self.storyboard instantiateViewControllerWithIdentifier:@"blue"];
        }
    }
    
    if(!self.yellowVC.view.superview){
        self.yellowVC.view.frame=self.view.frame;
        [self switchViewFromViewController:self.blueVC toViewController:self.yellowVC];
    }else{
        self.blueVC.view.frame=self.view.frame;
        [self switchViewFromViewController:self.yellowVC toViewController:self.blueVC];
    }
}

- (void)switchViewFromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    if(fromVC!=nil){
    [fromVC willMoveToParentViewController:nil];        //如果当前不显示此视图，就把它从父控制器和父视图中删除，好在receive memory warning时
    [fromVC.view removeFromSuperview];                  //删除
    [fromVC removeFromParentViewController];
    }
    [self addChildViewController:toVC];
    [self.view insertSubview:toVC.view atIndex:0];
    [toVC didMoveToParentViewController:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if(!self.yellowVC.view.superview){
        self.yellowVC=nil;
    }else
        self.blueVC=nil;
}

@end
